package org.CurrencyService;

import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class NBPService {

	private Map<String, String> filesName;
	
	
	public String getXMLFileFromNBP(String date, String URL, String extension) {
		String fileName = getFilesNameMap(URL,extension).get(date);
		return fileName;
	}
	
	private Map<String, String> getFilesNameMap( String URL, String extension) {

		if (filesName == null) {
			URL url;
			InputStream inputStream;
			filesName = new HashMap<String, String>();

			try {
				url = new URL(URL);
				inputStream = url.openStream();
				Scanner scanner = new Scanner(inputStream, "UTF-8");
				while (scanner.hasNextLine()) {
					String fileName = scanner.nextLine();

					if (fileName.startsWith("\uFEFF")) {
						fileName = fileName.substring(1);
					}

					String type = String.valueOf(fileName.charAt(0));
					if(type.equals("a")){
						String date = getDate(fileName);
						filesName.put(date, fileName + extension);
					}
				}
				scanner.close();
			} catch (Exception e) {
				filesName = new HashMap<String, String>();
			}
		}

		return filesName;
	}
	
	private String getDate(String text) throws Exception {
		String substring = text.substring(5);
		return substring;
	}
	
}
